package org.zhb.sql.query.login.controller;

import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.zhb.sql.query.core.util.EncryptionUtils;
import org.zhb.sql.query.model.User;

@RestController
public class LoginController {
	Logger log = LoggerFactory.getLogger(LoginController.class);

	@RequestMapping("/login")
	public ModelAndView login(User user, String checkcode, Model model, HttpServletRequest request) {
		log.info("用户开始登录");
		// 使用shiro 进行权限控制
		Subject userSubject = SecurityUtils.getSubject();
		// 将用户名和密码 封装成 令牌
		// 方法密码 必须 传递 char[]
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),
				EncryptionUtils.getEncryptionPassword(user.getPassword()).toCharArray());
		// 记住用户信息,设置记住用户信息--默认是不记住
		token.setRememberMe(true);
		try {
			// shiro 提供登陆方法
			userSubject.login(token);
			request.getSession().setAttribute("userName", user.getUserName());
			request.getSession().setAttribute("password", user.getPassword());
			// 跳转到主页
			return new ModelAndView("main");
		} catch (UnknownAccountException e) {
			e.printStackTrace();
			model.addAttribute("msg", "用户名不存在");
			return new ModelAndView("login");
		} catch (IncorrectCredentialsException e) {
			e.printStackTrace();
			model.addAttribute("msg", "密码错误");
			return new ModelAndView("login");
		}
	}

	/**
	 * 退出系统
	 * 
	 * @return
	 */
	@RequestMapping("/logout")
	public ModelAndView logout(HttpServletRequest request) {
		// 通知Subject 已经退出系统
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		// 销毁当前Session对象
		request.getSession().invalidate();
		return new ModelAndView("login");
	}

	@RequestMapping("/testSubject")
	public String testSubject(HttpServletRequest request) {
		// 通知Subject 已经退出系统
		Subject subject = SecurityUtils.getSubject();
		String sessionId = (String) subject.getSession().getAttribute("session_id");
		log.info("______________________值为:" + sessionId);
		return sessionId;
	}

}
